package module

import (
	"encoding/json"
	mysql "myapp/mysql"
	"myapp/structure"
	"net/http"
	"strings"

	_ "github.com/lib/pq"

	"github.com/labstack/echo"
)

// 登录
func Login(c echo.Context) error {

	user := new(structure.User)
	error := structure.Error
	ok := structure.Ok

	if err := c.Bind(user); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}

	if user.Name == "" || user.Password == "" {
		error.Msg = "用户名或密码错误"
		return c.JSON(http.StatusOK, error)
	}

	query := strings.Join([]string{"SELECT * FROM test WHERE name=\"", user.Name, "\" AND password=\"", user.Password, "\";"}, "")

	res, err := mysql.Query(query)

	if err != nil {
		error.Msg = "登录失败"
		return c.JSON(http.StatusOK, err)
	}

	if res[0] != nil {
		UserInfo := structure.UserInfo{
			Name: res[0]["name"],
			Age:  res[0]["age"],
			Six:  res[0]["six"],
		}
		mjson, _ := json.Marshal(UserInfo)
		mString := string(mjson)
		ok.Data = mString
		return c.JSON(http.StatusOK, ok)
	} else {
		error.Msg = "用户名或密码错误"
		return c.JSON(http.StatusOK, error)
	}

}
